<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <h2>个人信息</h2>
      </div>
      
      <el-form :model="profileForm" label-width="100px" class="profile-form">
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="真实姓名">
          <el-input v-model="profileForm.realName" disabled />
        </el-form-item>
        
        <el-form-item label="学号">
          <el-input v-model="profileForm.schoolNumber" disabled />
        </el-form-item>
        
        <el-form-item label="所属班级">
          <div>
            <div v-if="classList.length === 0">暂无班级信息</div>
            <div v-else>
              <div v-for="(item, idx) in classList" :key="item.classId" style="margin-bottom: 6px;">
                <el-tag type="info" style="margin-right: 8px;">{{ item.className }}</el-tag>
                <span style="color: #909399; font-size: 14px;">教师：{{ item.teacherName }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="邮箱">
          <div class="editable-item">
            <el-input v-model="profileForm.email" :disabled="!isEditingEmail" />
            <el-button type="primary" link @click="handleEmailEdit">
              {{ isEditingEmail ? '保存' : '修改' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <el-divider />
      
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUser } from '@/stores/userInfo'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import JSEncrypt from 'jsencrypt'
import { getStudentClassInfo } from '@/api/exam'

const router = useRouter()
const userStore = useUser()

// 表单数据
const profileForm = ref({
  username: '',
  realName: '',
  schoolNumber: '',
  email: '',
  className: ''
})

// 是否正在编辑邮箱
const isEditingEmail = ref(false)

// 新增班级信息列表
const classList = ref([])

// 加载个人信息（使用store中的数据）
const loadProfileInfo = () => {
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  profileForm.value = {
    username: userInfo.username || '',
    realName: userInfo.realName || '',
    schoolNumber: userInfo.schoolNumber || '',
    email: userInfo.email || '',
    className: userInfo.className || ''
  }
  // 获取班级信息
  if (userInfo.schoolNumber) {
    getStudentClassInfo(userInfo.schoolNumber).then(res => {
      if (res.code === 200 && Array.isArray(res.data)) {
        classList.value = res.data
      } else {
        classList.value = []
      }
    }).catch(() => {
      classList.value = []
    })
  }
}

// 处理邮箱编辑
const handleEmailEdit = async () => {
  if (isEditingEmail.value) {
    // 弹出密码输入框
    try {
      const { value: password } = await ElMessageBox.prompt('请输入密码以确认修改邮箱', '验证身份', {
        inputType: 'password',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{6,}$/,
        inputErrorMessage: '密码不能为空且不少于6位'
      })
      // 加密密码
      const publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7rYgHiByM6LUO1Z7ZD80OKWl1O16/c+D1zRrrP5rYq/YSG+ZuP7Bjx3tcOgFmKL97ifyAbdNn9RmvyqBRqMt8YlT9vYXYQ8MirWbnBulhC9Q9j2ab/sUIDd1qdDIuAxx5i7X377M/IIrMTe1HTID646kwkKr/eUMZ1EEjX/Xnk2lJxj3sSzKuQ+LPMLrFQ1LP1jM6MNB4auDkrQ2vNEoI41gMy0PEE168nYrQWGkRdbolDX5GNDragi9my+Uv4J2hvf1GYDzDFs+FLK5ceUKFkkoGRHouqxkizxNAC2GlMGkJdKp2NXmvDdYvXl8VGutHPN2TnL2c875dRBEHb81zQIDAQAB'
      const encrypt = new JSEncrypt()
      encrypt.setPublicKey(publicKey)
      const encryptedPassword = encrypt.encrypt(password)
      const username = profileForm.value.username
      const newEmail = profileForm.value.email
      const params = `password=${encodeURIComponent(encryptedPassword)}&newEmail=${encodeURIComponent(newEmail)}&username=${encodeURIComponent(username)}`
      const token = sessionStorage.getItem('token')
      const res = await fetch(`http://localhost:8080/updateEmail?${params}`, {
        method: 'GET',
        headers: {
          'Authorization': token ? `NERV_${token.replace(/^NERV_/, '')}` : ''
        }
      })
      const data = await res.json()
      if (data.code === 200) {
        // 保存邮箱到本地
        const userInfo = { ...userStore.userInfo, email: newEmail }
        userStore.setUserInfo(userInfo)
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
        ElMessage.success('邮箱修改成功')
        isEditingEmail.value = false
      } else {
        ElMessage.error(data.message || '邮箱修改失败')
      }
    } catch (e) {
      if (e !== 'cancel') ElMessage.error('邮箱修改已取消或失败')
    }
  } else {
    isEditingEmail.value = true
  }
}

onMounted(() => {
  loadProfileInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
}

.profile-header {
  margin-bottom: 30px;
}

.profile-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.profile-form {
  max-width: 500px;
}

.editable-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.password-section {
  margin-top: 30px;
}

.password-section h3 {
  margin: 0 0 20px;
  color: #303133;
  font-size: 18px;
}

.password-form {
  max-width: 500px;
}
</style>